package com.zidongxiangxi.sharding.job.core.listener;

import com.zidongxiangxi.sharding.job.core.ShardingJob;
import com.zidongxiangxi.sharding.job.core.node.LeaderNode;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;

/**
 * 主节点变化监听
 *
 * @author chenxudong
 * @date 2021/02/19
 */
public class LeaderNodeChangeListener extends AbstractNodeChangeListener {
    private final ShardingJob job;
    private final LeaderNode leaderNode;

    public LeaderNodeChangeListener(final ShardingJob job) {
        this.job = job;
        this.leaderNode = job.getLeaderNode();
    }

    @Override
    public boolean canHandleChange(String path, Type eventType) {
        return !job.isShutdown() && leaderNode.isLeaderInstancePath(path);
    }

    @Override
    void dealDataChange(String path, Type eventType, String data) {
        if (isActiveElection() || isLeaderCrashed(path, eventType)) {
            leaderNode.electLeader();
        }
    }

    private boolean isActiveElection() {
        return !leaderNode.hasLeader() ;
    }

    private boolean isLeaderCrashed(final String path, final Type eventType) {
        return leaderNode.isLeaderInstancePath(path) && Type.NODE_REMOVED == eventType;
    }
}
